<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>球机控制 - MediaMTX视频监控系统</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/all.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-icons.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/ptz.css') }}">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #1a2a6c, #2c3e50);
            color: #fff;
            min-height: 100vh;
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: #4e54c8;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #8f94fb;
        }

        .container {
            max-width: 1800px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            text-align: center;
            padding: 20px 0;
            margin-bottom: 30px;
            border-bottom: 2px solid rgba(255, 255, 255, 0.1);
        }

        h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            background: linear-gradient(90deg, #4e54c8, #8f94fb);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }

        .subtitle {
            color: #a0d2eb;
            font-size: 1.2rem;
            margin-top: 10px;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 25px;
            margin-bottom: 30px;
            transition: all 0.3s ease;
        }

        .dashboard.collapsed {
            grid-template-columns: 1fr 50px;
        }

        .video-container {
            background: rgba(0, 15, 30, 0.8);
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
            position: relative;
        }

        .video-player {
            width: 100%;
            height: auto;
            background: #000;
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 5;
            color: white;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #4e54c8;
            animation: spin 1s ease-in-out infinite;
            margin-bottom: 15px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .panel {
            background: rgba(0, 15, 30, 0.8);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
        }

        .panel-title {
            font-size: 1.4rem;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #4e54c8;
            color: #8f94fb;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #a0d2eb;
            font-weight: 500;
        }

        select,
        input {
            width: 100%;
            padding: 12px;
            border-radius: 8px;
            border: 1px solid #4e54c8;
            background: rgba(0, 20, 40, 0.7);
            color: white;
            font-size: 1rem;
        }

        .ptz-controls {
            background: rgba(0, 25, 50, 0.7);
            border-radius: 10px;
            margin-top: 60px;
        }

        .ptz-grid {
            display: grid;
            grid-template-areas:
                ". up up up ."
                "left left-up center right-up right"
                "left left-down center right-down right"
                ". down down down .";
            grid-gap: 15px;
            justify-items: center;
            align-items: center;
        }

        .ptz-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            font-size: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            user-select: none;
            transition: all 0.2s;
            background: #4e54c8;
            color: white;
            border: none;
        }

        .ptz-btn:hover {
            background: #6a71e6;
            transform: scale(1.1);
        }

        .ptz-btn:active {
            transform: scale(0.95);
        }

        .ptz-up {
            grid-area: up;
        }

        .ptz-down {
            grid-area: down;
        }

        .ptz-left {
            grid-area: left;
        }

        .ptz-right {
            grid-area: right;
        }

        .ptz-center {
            grid-area: center;
            background: #2c3e50;
        }

        .ptz-left-up {
            grid-area: left-up;
        }

        .ptz-left-down {
            grid-area: left-down;
        }

        .ptz-right-up {
            grid-area: right-up;
        }

        .ptz-right-down {
            grid-area: right-down;
        }

        .zoom-controls {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 60px;
        }
        .video-title {
            font-size: 0.9rem;
            color: #fff;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .zoom-btn {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            background: #4e54c8;
            color: white;
            border: none;
        }

        .zoom-btn:hover {
            background: #f1c40f;
        }

        .speed-control {
            margin-top: 30px;
            text-align: center;
        }

        .speed-slider {
            width: 100%;
            -webkit-appearance: none;
            height: 8px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            outline: none;
        }

        .speed-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #4e54c8;
            cursor: pointer;
        }

        .speed-value {
            font-size: 1.1rem;
            margin-top: 5px;
            color: #a0d2eb;
        }

        .error-box {
            background: rgba(231, 76, 60, 0.2);
            border: 1px solid #e74c3c;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            display: none;
        }

        .error-title {
            color: #e74c3c;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
        }

        .error-message {
            font-family: monospace;
            background: rgba(0, 0, 0, 0.3);
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            font-size: 0.95rem;
        }

        footer {
            text-align: center;
            margin-top: 40px;
            padding: 25px;
            color: #a0d2eb;
            font-size: 0.95rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        @media (max-width: 1100px) {
            .dashboard {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            h1 {
                font-size: 2.2rem;
            }

            .ptz-btn {
                width: 50px;
                height: 50px;
                font-size: 20px;
            }

            .zoom-btn {
                width: 40px;
                height: 40px;
                font-size: 16px;
            }
        }
        .breadcrumb {
            font-size: 14px;
            margin-bottom: 10px;
            color: #666;
        }

        .breadcrumb a {
            color: #4a6fa5;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        .breadcrumb .separator {
            margin: 0 5px;
            color: #999;
        }
    </style>
</head>
<body>
<div class="container">

    <div class="header">
        <div class="breadcrumb">
            <a href="/index">主页</a>
            <span class="separator">/</span>
            <span>云台控制</span>
        </div>
    </div>

    <div class="dashboard">
        <div class="video-container">
            <div class="video-cell" data-camera-id=”1">
                <div class="video-header">
                    <div class="video-title">视频窗口</div>
                </div>
                <div class="video-wrapper">
                    <div class="video-grid-container" id="videoGrid">
                        <video class="video-player" autoplay playsinline></video>
                        <!-- 视频窗口将动态生成 -->
                    </div>
                    <div class="loading-overlay" style="display:none;">
                        <div class="spinner"></div>
                        <p>正在连接球机...</p>
                    </div>
                </div>
                <div class="error-box" style="display:none;">
                    <h3 class="error-title"><i class="fas fa-exclamation-triangle"></i> 连接错误</h3>
                    <div class="error-message"></div>
                    <button class="control-btn btn-danger retry-btn" style="margin-top: 15px; width: 100%;">
                        <i class="fas fa-redo-alt"></i> 重试连接
                    </button>
                </div>

            </div>

        </div>
        <div class="panel">
            <h2 class="panel-title"><i class="fas fa-sliders-h"></i> 云台控制面板</h2>
            <div class="form-group">
                <label><i class="fas fa-camera"></i> 选择摄像头</label>
                <select id="cameraSelect" class="form-control">
                </select>
            </div>

            <div class="ptz-controls">
                <div class="pie">
                    <div class="slice-one slice" id="ptzUp">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-two slice" id="ptzRightUp">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-three slice" id="ptzRight">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-four slice" id="ptzRightDown">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-five slice" id="ptzDown">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-six slice" id="ptzLeftDown">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-seven slice" id="ptzLeft">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="slice-eight slice" id="ptzLeftUp">
                        <div class="dv">
                            <div class="sj"></div>
                        </div>
                    </div>
                    <div class="center">
                        <div class="inner" id="ptzStop">
                        </div>

                    </div>
                </div>

                <div class="zoom-controls">
                    <button class="zoom-btn" id="zoomIn"><i class="fas fa-search-plus"></i></button>
                    <button class="zoom-btn" id="zoomOut"><i class="fas fa-search-minus"></i></button>
                </div>

                <div class="speed-control">
                    <label>控制速度</label>
                    <input type="range" class="speed-slider" min="1" max="100" value="50" id="speedSlider">
                    <div class="speed-value" id="speedValue">50</div>
                </div>
            </div>

            <div class="error-box" id="errorBox">
                <h3 class="error-title"><i class="fas fa-exclamation-triangle"></i> 连接错误</h3>
                <div class="error-message" id="errorMessage"></div>
                <button id="retryBtn" class="control-btn btn-danger" style="margin-top: 15px; width: 100%;">
                    <i class="fas fa-redo-alt"></i> 重试连接
                </button>
            </div>
        </div>
    </div>

    <footer>
        &copy; 2025 视频监控系统 | 版本 1.0.0
    </footer>
</div>

<script>
    // 获取DOM元素
    const speedSlider = document.getElementById('speedSlider');
    const speedValue = document.getElementById('speedValue');
    const errorBox = document.getElementById('errorBox');
    const errorMessage = document.getElementById('errorMessage');
    const retryBtn = document.getElementById('retryBtn');
    const cameraSelect = document.getElementById('cameraSelect')

    let currentSpeed = 50;
    let isMouseDown = false;
    let currentDirection = null;
    let cameraList = [];    // 存储摄像头列表
    let activeConnections = {}; // 存储WebRTC连接
    let currentCameraId = 0;

    // 初始化页面
    document.addEventListener('DOMContentLoaded', async function () {
        // 加载摄像机列表
        cameraList = await loadCameras();
        currentCameraId = cameraSelect.value;

        // PTZ控制按钮事件
        const ptzButtons = {
            ptzUp: 'up',
            ptzDown: 'down',
            ptzLeft: 'left',
            ptzRight: 'right',
            ptzLeftUp: 'left_up',
            ptzLeftDown: 'left_down',
            ptzRightUp: 'right_up',
            ptzRightDown: 'right_down'
        };

        // 更新速度显示
        speedSlider.addEventListener('input', function () {
            currentSpeed = parseInt(this.value);
            speedValue.textContent = currentSpeed;
        });
        retryBtn.addEventListener('click', async function () {
            await connectToCamera(currentCameraId);
        });

        // 摄像头选择变化
        cameraSelect.addEventListener('change', async (e) => {
            const cameraId = e.target.value;
            if(!cameraId) return;
            const camera = cameraList.find(c => c.id === parseInt(cameraId));
            if(!camera) return;
            let videoTitle = document.querySelector('.video-title');
            videoTitle.innerHTML = camera.name;
            currentCameraId = camera.id;
            await connectToCamera(cameraId);
        });

        // 为每个PTZ按钮添加事件
        Object.keys(ptzButtons).forEach(btnId => {
            const btn = document.getElementById(btnId);
            const direction = ptzButtons[btnId];
            btn.addEventListener('mousedown', function () {
                isMouseDown = true;
                currentDirection = direction;

                controlPTZ(direction, currentSpeed, 1); // 0表示持续控制
            });

        });

        // 变焦控制
        document.getElementById('zoomIn').addEventListener('click', function () {
            controlPTZ('zoom_in', currentSpeed, 1);
        });

        document.getElementById('zoomOut').addEventListener('click', function () {
            controlPTZ('zoom_out', currentSpeed, 1);
        });

        // 重试按钮
        retryBtn.addEventListener('click', function () {
            connectToCamera(currentCameraId);
        });
    });

    // 控制PTZ
    function controlPTZ(direction, speed, duration) {
        console.log(`PTZ控制: 方向=${direction}, 速度=${speed}, 持续时间=${duration}`);
        // 这里应该是实际的API请求
        fetch(`api/cameras/${currentCameraId}/ptz`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify({
                direction: direction,
                speed: speed,
                duration: duration
            })
        })
        .then(response => console.log(response))
        .then(data => {
            console.log('PTZ控制成功:', data);
        })
        .catch(error => {
            console.error('PTZ控制失败:', error);
        });
    }

    // 连接到摄像头
    async function connectToCamera(cameraId) {
        const camera = cameraList.find(c => c.id === parseInt(cameraId));
        if (!camera) return;
        const videoCell = document.querySelector(`.video-cell`);
        if (!videoCell) return;

        const videoWrapper = videoCell.querySelector('.video-wrapper');
        const video = videoCell.querySelector('.video-player');
        const loading = videoWrapper.querySelector('.loading-overlay');
        const errorBox = videoCell.querySelector('.error-box');
        const errorMessage = videoCell.querySelector('.error-message');

        // 显示加载状态
        loading.style.display = 'flex';
        errorBox.style.display = 'none';
        video.srcObject = null;
        video.src = '';

        // 清除之前的连接
        if (activeConnections[0]) {
            activeConnections[0].close();
            delete activeConnections[0];
        }

        try {
            // 设置超时 (30秒)
            const timeout = setTimeout(() => {
                throw new Error('连接超时 (30秒)');
            }, 30000);

            // 尝试WebRTC (WHEP)
            await connectWithWebRTC(camera, video, loading, errorBox, errorMessage);

            clearTimeout(timeout);
        } catch (error) {
            console.error('WebRTC连接失败:', error);
            errorMessage.textContent = `WebRTC连接失败: ${error.message}`;
            errorBox.style.display = 'block';
            loading.style.display = 'none';
        }
    }

    // 使用WebRTC连接
    async function connectWithWebRTC(camera, video, loading, errorBox, errorMessage) {

        try {
            // 1. 创建PeerConnection
            const pc = new RTCPeerConnection({
                iceServers: [
                    {urls: 'stun:stun.l.google.com:19302'}
                ]
            });

            // 存储连接以便后续管理
            activeConnections[0] = pc;

            // 2. 设置事件处理器
            pc.ontrack = (event) => {
                if (event.track.kind === 'video') {
                    video.srcObject = event.streams[0];
                    loading.style.display = 'none';
                }
            };

            pc.oniceconnectionstatechange = () => {
                if (pc.iceConnectionState === 'failed') {
                    errorMessage.textContent = 'ICE连接失败';
                    errorBox.style.display = 'block';
                }
            };

            // 3. 添加视频接收器
            pc.addTransceiver('video', { direction: 'recvonly'});

            // 4. 创建Offer
            const offer = await pc.createOffer();
            await pc.setLocalDescription(offer);

            // 5. 通过后端发送Offer到MediaMTX
            const token = localStorage.getItem('token');
            const response = await fetch(`/api/stream/${camera.id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    offer: offer.sdp
                })
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || '信令服务器错误');
            }

            // 6. 处理Answer
            const data = await response.json();
            await pc.setRemoteDescription({
                type: data.type,
                sdp: data.sdp
            });

        } catch (error) {
            console.error('WebRTC连接失败:', error);
            errorMessage.textContent = `连接失败: ${error.message}`;
            errorBox.style.display = 'block';
            loading.style.display = 'none';

            // 清理失败的连接
            if (activeConnections[0]) {
                activeConnections[0].close();
                delete activeConnections[0];
            }

            // 处理认证错误
            if (error.message.includes('Unauthorized')) {
                localStorage.removeItem('token');
                window.location.href = '/login';
            }
        }
    }

    // 加载摄像头列表
    async function loadCameras() {
        let cameras = null;
        try {
            const response = await fetch('/api/cameras');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            cameras = data['cameras'];
            if (cameras && cameras.length > 0) {
                cameraSelect.innerHTML = '<option value="">-- 请选择摄像头 --</option>' +
                    cameras.map(camera =>
                        `<option value="${camera.id}">${camera.name} (${camera.ip})</option>`
                    ).join('');
            } else {
                cameraSelect.innerHTML = '<option value="">-- 没有可用的摄像头 --</option>';
            }
        } catch (error) {
            console.error('加载摄像头列表失败:', error);
        }
        return cameras
    }
</script>
</body>
</html>